package com.example.controller;

import com.alibaba.excel.EasyExcel;
import com.example.entity.InfoExcel;
import com.example.entity.Sign;
import com.example.entity.StudentSign;
import com.example.entity.User;
import com.example.service.SignService;
import com.example.service.StudentSignService;
import com.example.service.UserService;
import com.example.utils.R;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/sign")
public class SignController {
    @Autowired
    private SignService signService;
    @Autowired
    private UserService userService;
    @Autowired
    private StudentSignService studentSignService;


    /**
     * 接收教师定义的签到数据并返回id
     * @param sign
     * @return
     */
    @PostMapping("/generateQRCode")
    public R<HashMap<String,Object>> generateQRCode(@RequestBody Sign sign) {

        return R.success(signService.generateQRCode(sign));

    }

    /**
     * 学生签到
     * @param student
     * @param signId
     * @return
     * @throws ParseException
     */
    @PostMapping("/student")
    public R<HashMap<String,Object>> studentSignIn(@RequestBody StudentSign student, @RequestParam(value = "signId") String signId) throws ParseException {

        return R.success(signService.studentSignIn(student,signId));
    }

    //    导出签到信息
    @GetMapping("/download")
    public void download(@RequestParam(value = "signId") String signId,@RequestParam(value = "className") String className, HttpServletResponse response) throws Exception {

        Sign sign = signService.getSignById(signId);//根据signId查询签到信息
        String signClassCode = sign.getClassCode();//根据sign_id拿到classCode
        List<User> userList = userService.getUserByClassCode(signClassCode);//根据classCode拿到整个班级的成员
        List<InfoExcel> infoExcelList = new ArrayList<>();//创建导出excel的对象集合
        for (User user : userList) {
//            将要导出的班级信息放入infoExcelList
            InfoExcel infoExcel = new InfoExcel();
            infoExcel.setAccount(user.getAccount());
            infoExcel.setUserName(user.getUserName());
//            根据sign_id和account查询签到记录，若函数返回值不为空，则将签到记录放入infoExcelList
            StudentSign studentSign = studentSignService.getInfoBySignIdAndAccount(signId, user.getAccount());
            if (studentSign != null) {
                infoExcel.setFlag("已签到");
            } else {
                infoExcel.setFlag("未签到");
            }
            infoExcelList.add(infoExcel);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        Calendar instance = Calendar.getInstance();
        String nowDate = String.format("%02d%02d", instance.get(Calendar.MONTH) + 1, instance.get(Calendar.DAY_OF_MONTH));

        String fileName = URLEncoder.encode(className.concat(nowDate).concat("签到数据表"), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), InfoExcel.class).sheet("sheet").doWrite(infoExcelList);

        return;
    }
}
